package cn.itrip.auth.service;

import cn.itrip.common.PropertiesUtils;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SmsServiceImpl implements  SmsService {


    private String accessKeyId = PropertiesUtils.get("sms.properties", "sms.accessKeyId");
    private String secret = PropertiesUtils.get("sms.properties", "sms.secret");


    @Override
    public boolean sendMessage(String phoneNumbers, String SignName, String TemplateCode, String TemplateParam) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", SignName);
        request.putQueryParameter("TemplateCode", TemplateCode);
        request.putQueryParameter("TemplateParam", TemplateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            Map map =JSON.parseObject(response.getData());
            return map.get("Message").equals("OK");
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }


    public static void main(String[] args) {
        SmsService smsService = new SmsServiceImpl();
        boolean rs =smsService.sendMessage("18814120272","圣乡堂","SMS_169900031","{'code':123456}");
        if(rs){
            System.out.println("发送短信成功");
        }
    }

}
